<template>
  <div class="box">
    <h2>筛选地震范围</h2>
    <div class="list">
      <span class="title">日期: </span>
      <el-date-picker
        v-model="formData.time"
        type="daterange"
        range-separator="~"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        @visible-change="handleOpen"
      />
      <!-- <darkInput v-model="formData.st" placeholder="开始时间" type="timedate" size="small" style="width: 150px" />
            ~
            <darkInput v-model="formData.st" placeholder="开始时间" size="small"  style="width: 150px" /> -->
    </div>
    <div class="list" style="justify-content: center">
      <el-radio-group v-model="formData.now">
        <el-radio :value="0">今年</el-radio>
        <el-radio :value="1">近一年</el-radio>
        <el-radio :value="2">全部</el-radio>
      </el-radio-group>
    </div>
    <div class="list">
      <span class="title">震级: </span>
      <darkInput
        v-model="formData.minscope"
        placeholder=""
        size="small"
        style="width: 140px; border: 1px solid #b9eeff"
      />
      ~
      <darkInput
        v-model="formData.maxscope"
        placeholder=""
        size="small"
        style="width: 140px; border: 1px solid #b9eeff"
      />
    </div>
    <div class="list">
      <span class="title">地震名称: </span>
      <darkInput
        v-model="formData.name"
        placeholder=""
        size="small"
        style="width: 295px; border: 1px solid #b9eeff"
      />
    </div>
    <div class="list">
      <span class="title">震中距: </span>
      <darkInput
        v-model="formData.km"
        placeholder=""
        size="small"
        style="width: 255px; border: 1px solid #b9eeff"
      />
      <span style="margin-left: 10px"> km</span>
    </div>
    <div class="list">
      <span class="title">行政区划: </span>
      <el-select
        v-model="formData.shen"
        placeholder="省"
        @visible-change="handleOpen"
        style="width: 95px; margin-right: 10px"
        @change="loadCity"
      >
        <el-option
          v-for="(item, index) in shenOptions"
          :key="index"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-select
        v-model="formData.shi"
        placeholder="市"
        @visible-change="handleOpen"
        style="width: 95px; margin-right: 10px"
        @change="loadCounties"
      >
        <el-option
          v-for="(item, index) in shiOptions"
          :key="index"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-select
        v-model="formData.xian"
        placeholder="区县"
        @visible-change="handleOpen"
        style="width: 95px"
      >
        <el-option
          v-for="(item, index) in xianOptions"
          :key="index"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
    </div>

    <div class="list">
      <span class="title">震害: </span>&nbsp;死亡&nbsp;&nbsp;
      <darkInput
        v-model="formData.minharm"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      ~
      <darkInput
        v-model="formData.maxharm"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      <span style="margin-left: 10px"> 人</span>
    </div>

    <div class="list">
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="title">受伤 </span>
      <darkInput
        v-model="formData.minwounded"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      ~
      <darkInput
        v-model="formData.maxwounded"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      <span style="margin-left: 10px"> 人</span>
    </div>
    <div class="list">
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="title"
        >经济损失
      </span>
      <darkInput
        v-model="formData.minmoney"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      ~
      <darkInput
        v-model="formData.maxmoney"
        placeholder=""
        size="small"
        style="width: 100px; border: 1px solid #b9eeff"
      />
      <span style="margin-left: 10px"> 万</span>
    </div>
    <div class="list" style="justify-content: center">
      <el-button align="right" type="primary" style="float: right" @click="getData">检索</el-button>
      <el-button align="right" type="primary" style="float: right" @click="clearForm"
        >清空</el-button
      >
      <el-button align="right" type="primary" style="float: right" @click="generateWord"
        >结果导出</el-button
      >
    </div>
  </div>

  <teleport to="body">
    <div ref="popup" id="1c12" class="popup">
      <autoDialog
        :isuseDraggable="false"
        size="small"
        :title="poiname"
        :isFixed="false"
        @close="
          () => {
            hidePopup && hidePopup()
          }
        "
      >
        <div v-if="earthQuakeType == 2">
          <div class="title"
            >发震时刻&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.time }}</span></div
          >
          <div class="title"
            >发震位置&nbsp;:&nbsp;<span class="desc"
              >东经{{ earthQuakeInfo.location[0] }}，北纬{{ earthQuakeInfo.location[1] }}</span
            ></div
          >
          <div class="title"
            >震级&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.shockLevel }}级</span></div
          >
          <div class="title"
            >震源深度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.depth }}公里</span></div
          >
          <div class="title"
            >震中距&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.zzj }}公里</span></div
          >
        </div>
        <div v-else>
          <div style="height: 100%; line-height: 30px; font-size: 18px">
            <div class="title"
              >发震时刻&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.time }}</span></div
            >
            <div class="title"
              >发震位置&nbsp;:&nbsp;<span class="desc"
                >东经{{ earthQuakeInfo.location[0] }}，北纬{{ earthQuakeInfo.location[1] }}</span
              ></div
            >
            <div class="title"
              >震级&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.shockLevel }}级</span></div
            >
            <div class="title"
              >震源深度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.depth }}公里</span></div
            >
            <div class="title"
              >震中距&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.zzj }}公里</span></div
            >
            <div class="title"
              >死亡人数&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.die }}人</span></div
            >
            <div class="title"
              >受伤人数&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.ss }}人</span></div
            >
            <div class="title"
              >经济损失&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.jjss }}万元</span></div
            >
          </div>
        </div>
      </autoDialog>
    </div>
  </teleport>
</template>

<script setup>
import { ref, defineEmits, watch } from 'vue'

import {
  Packer,
  Document,
  Paragraph,
  TextRun,
  Table,
  TableRow,
  TableCell,
  WidthType,
  VerticalAlign,
  AlignmentType
} from 'docx'
import {
  createDzRange,
  createPopup,
  calculateDistanceWithArrays
} from '../../../../api/gis3d/maputils'
import {
  createPointAndToView,
  createPoint,
  createReferencePoint
} from '../../../../api/gis3d/maputils'
import { getHistoryQuakeList } from '../../../../api/earthquake'
import { useMapStoreStore } from '../../../../stores/index'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { getProvinces, getCities, getCounties, getLocation } from '../../../../api/district'

const emits = defineEmits(['closeTime'])
const store = useMapStoreStore()

const earthQuakeType = ref(-1) //1 震害地震 2历史地震
const formData = ref({
  time: [],
  now: 0,
  minscope: '',
  maxscope: '',
  name: '',
  km: '',
  shen: '',
  shi: '',
  xian: '',
  minharm: '',
  maxharm: '',
  minwounded: '',
  maxwounded: '',
  minmoney: '',
  maxmoney: ''
})

const xianOptions = ref([])
const shiOptions = ref([])
const shenOptions = ref([])

const updateDateRange = () => {
  const now = dayjs()
  switch (formData.value.now) {
    case 0:
      // 今年
      formData.value.time = [dayjs().startOf('year'), now]
      break
    case 1:
      // 近一年
      formData.value.time = [now.subtract(1, 'year'), now]
      break
    case 2:
      // 全部（1970 到现在）
      formData.value.time = [dayjs('1970-01-01'), now]
      break
  }
}
// 监听 formData.now 的变化，以便及时更新日期范围
watch(() => formData.value.now, updateDateRange, { immediate: true })

const clearForm = () => {
  formData.value = {
    time: [],
    now: 0,
    minscope: '',
    maxscope: '',
    name: '',
    km: '',
    shen: '',
    shi: '',
    xian: '',
    minharm: '',
    maxharm: '',
    minwounded: '',
    maxwounded: '',
    minmoney: '',
    maxmoney: ''
  }
  hidePopup && hidePopup()
  closePopup && closePopup()
  closePopup = null
  hidePopup = null
  updateDateRange()
  clearEntity()
}

const handleOpen = (e) => {
  emits('closeTime', e)
}

function generateWord() {
  if (allData.length === 0) {
    ElMessage({
      message: '暂无历史数据',
      type: 'warning'
    })
    return
  }
  // 创建一个新的文档
  const doc = new Document({
    sections: [
      {
        properties: {
              page: {
                  margin: {
                    top:1.27*567,
                    right:  1.8*567,
                    bottom: 1.27*567,
                    left:  1.8*567,
                },
        }
        },
        children: [
          // new Paragraph({
          //   children: [new TextRun('这是生成的 Word 表格')]
          // }),
          // 创建一个表格
          ...createTable()
        ]
      }
    ]
  })
  // 使用 Packer 将文档打包成 Blob
  Packer.toBlob(doc).then((blob) => {
    // 创建一个链接并触发下载
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '历史地震.docx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
}

function createTable() {
  // 定义表格数据
  const data = [
    ['序号', '发震时间', '经度（度）', '纬度（度）', '震级', '宏观震中', '震中距(公里)', '震害基本情况']
  ]
  var index = 1
  let sortArr = []
  for (const e of allData) {
    var arr = [
      index + '',
      dayjs(e.seismDate + '' + e.h + ':' + e.m + ':' + e.s).format('YYYY-MM-DD HH:mm:ss') + '',
      e.lon + '',
      e.lat + '',
      e.shockLevel + '',
      e.macroscopic,
      e.zzj + '',
      e.causeDisaster
    ]
    sortArr.push(arr)
    index++
  }
sortArr.sort((a, b) => {
    return dayjs(b[1]).diff(dayjs(a[1])) > 0? 1 : -1;
});
var restIndex = 1;
for (const element of sortArr) {
  element[0] = restIndex+'';
  restIndex++;
}
  const newdata = data.concat(sortArr)
  const cellwidth = [2505, 3505, 2505, 2505, 2505, 5505, 3505, 7505]

  // 创建标题段落
  const titleParagraph = new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: {
      before: 15 * 20, // 适当增加标题前间距，单位转换为Twips
      after: 15 * 20
    },
    children: [
      new TextRun({
        text: '（按时间排序）', // 这里定义标题文本，可根据实际需求修改
        bold:true,
        size: 36 // 设置标题字体大小，具体可根据实际效果调整合适的值，单位可能依库而定，此处示意为相对大小值
      })
    ]
  })

  // 创建表格
  const table = new Table({
    rows: newdata.map((row, rowIndex) => {
      return new TableRow({
        verticalAlign: VerticalAlign.CENTER,
        children: row.map((cell, cellIndex) => {
          return new TableCell({
            width: {
              //  size:3505,
              size: cellwidth[cellIndex],
              type: WidthType.DXA
            },
            verticalAlign: VerticalAlign.CENTER,
            children: [
              new Paragraph({
                alignment: AlignmentType.CENTER,
                spacing: {
                  before: 10 * 20, // 上下内边距转换为Twips（1 Twip = 1/1440 英寸，Word中的单位）
                  after: 10 * 20
                },
                padding: {
                  left: 15 * 20, // 左右内边距转换为Twips
                  right: 15 * 20
                },
                children: [
                  new TextRun({
                    text: cell,
                    bold: rowIndex === 0, // 如果是表头行（索引为0）则字体加粗
                    size:rowIndex === 0 ? 26 : 22 // 设置表格内文字字体大小，同样可根据实际调整
                  })
                ]
              })
            ]
          })
        })
      })
    })
  })
 
 let formd = formData.value;
 const mimeFooter = {
  '时间':dayjs(formd.time[0]).format('YYYY年MM月DD日') +"----"+ dayjs(formd.time[1]).format('YYYY年MM月DD日'),
  '震级':"无",
  '地震名称':formd.name || "无",
  '震中距':formd.km ?formd.km +"km": "无",
  '行政区划': formd.shen ? formd.shen + formd.shi + formd.xian  :"无",
  '死亡':"无",
  '受伤':"无",
  '经济损失':"无",
 }
 if(formd.minscope){
  mimeFooter.震级 = "最小" + formd.minscope +"级"
 }
 if(formd.maxscope){
  mimeFooter.震级 = "最大" + formd.maxscope +"级"
 }
 if(formd.maxscope && formd.minscope){
  mimeFooter.震级 =  formd.minscope +"级"+"-"+formd.maxscope+"级"
 }

if(formd.minharm){
  mimeFooter.死亡 = "最小" + formd.minharm +"人"
 }
 if(formd.maxharm){
  mimeFooter.死亡 = "最大" + formd.maxharm +"人"
 }
 if(formd.maxharm && formd.minharm){
  mimeFooter.死亡 =  formd.minharm +"人"+"-"+formd.maxharm+"人"
 }

 if(formd.minwounded){
  mimeFooter.受伤 = "最小" + formd.minwounded +"人"
 }
 if(formd.maxwounded){
  mimeFooter.受伤 = "最大" + formd.maxwounded +"人"
 }
 if(formd.maxwounded && formd.minwounded){
  mimeFooter.受伤 =  formd.minwounded +"人"+"-"+formd.maxwounded+"人"
 }

  if(formd.minmoney){
  mimeFooter.经济损失 = "最小" + formd.minmoney +"万元"
 }
 if(formd.maxmoney){
  mimeFooter.经济损失 = "最大" + formd.maxmoney +"万元"
 }
 if(formd.maxmoney && formd.minmoney){
  mimeFooter.经济损失 =  formd.minmoney +"万元"+"-"+formd.maxmoney+"万元"
 }

   const filteredObj = Object.entries(mimeFooter).reduce((acc, [key, value]) => {
    if (value !== '无' && value !== null && value !== undefined) {
      acc[key] = value
    }
    return acc
  }, {})

  const footerParagraph = [
    new Paragraph({
      alignment: AlignmentType.LEFT,
      spacing: {
        before: 10 * 20,
        after: 10 * 20
      },
      children: [
        new TextRun({
          text: '（筛选条件说明）',
            bold:true,
          size: 30 // 设置说明文字字体大小，可按需调整
        })
      ]
    })
  ]

  for (const element in filteredObj) {

    let a =  new Paragraph({
      alignment: AlignmentType.LEFT,
      spacing: {
        before: 10 * 20,
        after: 10 * 20
      },
      children: [
          new TextRun({
                text: element + ":",
                bold: true,
                size: 24
            }),
            new TextRun({
                text: filteredObj[element],
                size: 24
            })
      ]
    })
    footerParagraph.push(a)
  }
  // 创建尾部文字说明段落
  const content = [titleParagraph, table, ...footerParagraph]
  return content
}

const popup = ref(null)
let closePopup = null
let hidePopup = null
let updateH = null
const poihtml = ref('')
const poiname = ref('')

const getData = () => {
  let e = formData.value
  // if (e.minscope == '' || e.maxscope == '') {
  //   ElMessage({
  //     message: '请输入震级',
  //     type: 'error',
  //     plain: true
  //   })
  //   return
  // }
  const prarms = {}
  prarms.startDate = dayjs(e.time[0]).format('YYYYMMDD')
  prarms.endDate = dayjs(e.time[1]).format('YYYYMMDD')
  prarms.queryDateRange = e.now
  prarms.shockLevelMin = e.minscope || 0
  prarms.shockLevelMax = e.maxscope || 10

  //地震名称
  prarms.quakeName = e.name
  //震中距
  prarms.lon = store.earthquakeInfo.longitude
  prarms.lat = store.earthquakeInfo.latitude
  prarms.centerDistanse = e.km

  prarms.provinceCode = e.shen == '默认' ? '' : e.shen
  prarms.cityCode = e.shi == '默认' ? '' : e.shi
  prarms.countyCode = e.xian
  prarms.dieMin = e.minharm
  prarms.dieMax = e.maxharm
  prarms.injuredMin = e.minwounded
  prarms.injuredMax = e.maxwounded

  prarms.economicMin = e.minmoney
  prarms.economicMax = e.maxmoney

  const filteredObj = Object.entries(prarms).reduce((acc, [key, value]) => {
    if (value !== '' && value !== null && value !== undefined) {
      acc[key] = value
    }
    return acc
  }, {})

  getHistoryQuakeList(filteredObj).then((e) => {
    // if (e.length > 10) {
    //   e = e.slice(0, 10)
    // }
    if (!closePopup) {
      ;({ closePopup, hidePopup, updateH } = createPopup(
        popup.value,
        35,
        getPoiData,
        'history-point'
      ))
    }

    clearEntity()
    loadEarthQuake()
    loadHistoryEarthQuakeData(e)
  })
}

let allData = []
let entityHistory = []
const loadHistoryEarthQuakeData = (data) => {
  allData = data

  for (const e of data) {
    e.zzj = calculateDistanceWithArrays(
      [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude],
      [e.lon, e.lat]
    )
    e.zzj = Math.round(e.zzj)

    var info = {
      position: [e.lon, e.lat],
      data: e,
      color: '#24acf2',
      size: 20,
      // url: e.die > 0 ? '/static/assets/poi/zh.png' : '/static/assets/poi/ls.png',
      type: 'history-point'
    }
    if (e.die > 0 || e.injured > 0 || e.economic > 0) {
      info.color = '#fd231a'
    }
    // var pi = e.shockLevel < 5 ? [5, 10, 20] : [5, 10, 20, 50, 100]
    // var { ellipses } = createDzRange(e.lat, e.lon, pi)
    // map3d.printCirclesText([e.lon,e.lat], pi);
    var entity = createReferencePoint(info)
    entityHistory.push(entity)
  }
}

const loadEarthQuake = () => {
  let center = [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude]
  let arrRadius = [100, 50, 20, 10]
  map3d.printCirclesText(center, arrRadius)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      store.earthquakeInfo.longitude,
      store.earthquakeInfo.latitude,
      120000
    ),
    duration: 1 // 飞行时间（s）
  })
}

const clearEntity = () => {
  // if(entityHistory.length === 0)return;

  for (const e of entityHistory) {
    viewer.entities.remove(e)
  }
  map3d.printCirclesText()
  entityHistory = []
  allData = []
}

const earthQuakeInfo = ref({
  time: '',
  location: [],
  depth: '30',
  zzj: '10',
  die: '10',
  ss: '10',
  jjss: '123'
})
const getPoiData = (data) => {
  earthQuakeType.value = data.die > 0 || data.injured > 0 || data.economic > 0 ? 1 : 2
  poiname.value = data.macroscopic
  earthQuakeInfo.value.time = dayjs(
    data.seismDate + '' + data.h + ':' + data.m + ':' + data.s
  ).format('YYYY-MM-DD HH:mm:ss')
  earthQuakeInfo.value.location = [data.lon, data.lat]
  earthQuakeInfo.value.depth = data.depth
  earthQuakeInfo.value.zzj = calculateDistanceWithArrays(
    [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude],
    [data.lon, data.lat]
  )
  earthQuakeInfo.value.shockLevel = data.shockLevel
  earthQuakeInfo.value.die = data.die
  earthQuakeInfo.value.ss = data.injured
  earthQuakeInfo.value.jjss = data.economics || 0
}
const initProvinces = () => {
  getProvinces().then((e) => {
    shenOptions.value = e
    shenOptions.value.unshift({
      code: '',
      name: '默认'
    })
  })
}
const loadCity = () => {
  shiOptions.value = []
  formData.value.shi = ''
  xianOptions.value = []
  formData.value.xian = ''
  if (formData.value.shen == '' || formData.value.shen == '默认') {
    return
  }

  getCities({ provinceCode: formData.value.shen }).then((e) => {
    shiOptions.value = e
    shiOptions.value.unshift({
      code: '',
      name: '默认'
    })
  })
}
const loadCounties = () => {
  xianOptions.value = []
  formData.value.xian = ''
  if (formData.value.shi == '' || formData.value.shi == '默认') {
    return
  }
  getCounties({ provinceCode: formData.value.shen, cityCode: formData.value.shi }).then((e) => {
    xianOptions.value = e
  })
}

onMounted(() => {
  initProvinces()
})
</script>

<style lang="scss" scoped>
.popup {
  position: fixed;
  display: none; /* 初始隐藏 */
  width: 450px;
  .title {
    font-size: 16px;
    color: #b9eeff;
    line-height: 26px;
    span {
      color: #fff;
    }
  }
}
.el-button {
  height: 40px;
  border-radius: 4px;

  background: linear-gradient(90deg, #3f97f0 3%, #003f82 99%);
}
:deep(.el-date-editor) {
  --el-input-bg-color: transparent;
  --el-text-color-primary: #fff;
}
.el-radio {
  color: #b9eeff;
}
:deep(.el-date-editor .el-range-input) {
  color: #b9eeff;
}
:deep(.el-date-editor .el-range-input::placeholder) {
  color: #b9eeff;
}
:deep(.el-select__placeholder) {
  color: #b9eeff;
}
:deep(.el-input__wrapper) {
  background-color: transparent;
  color: #b9eeff;
  background-color: rgba(0, 25, 51, 0.8);
  border: 1px solid #b9eeff;
  outline: none;
  box-shadow: none;
}
:deep(.el-select__placeholder.is-transparent) {
  color: #b9eeff;
}
:deep(.el-select__wrapper) {
  background-color: rgba(0, 25, 51, 0.8);
  border: 1px solid #b9eeff;
  outline: none;
  box-shadow: none;
}
:deep(.el-select__caret) {
  color: #b9eeff;
}
.box {
  padding: 10px;
  color: #b9eeff;
  h2 {
    font-style: italic;
    font-size: 24px;
    margin: 0;
    background: linear-gradient(180deg, #ffffff 0%, #c9f3ff 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
  }
  .list {
    display: flex;
    align-items: center;
    width: 100%;
    margin-top: 15px;
    .title {
      width: 70px;
      text-align: right;
      margin-right: 10px;
    }
  }
}
</style>